package cn.wyl.pet.service.impl;

import cn.wyl.basic.exception.BusinessException;
import cn.wyl.basic.util.AxiousResult;
import cn.wyl.basic.util.BaiduAuditUtils;
import cn.wyl.pet.domain.Product;
import cn.wyl.pet.domain.ProductDetail;
import cn.wyl.pet.mapper.ProductDetailMapper;
import cn.wyl.pet.mapper.ProductMapper;
import cn.wyl.pet.service.IProductService;
import cn.wyl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {
    @Autowired
    ProductMapper productMapper;
    @Autowired
    ProductDetailMapper productDetailMapper;

    @Transactional
    @Override
    public void remove(Long id) {

        productMapper.remove(id);
        productDetailMapper.removeByProductId(id);
    }

    @Transactional
    @Override
    public void patchDel(List<Long> ids) {
       for(Long id:ids){
           remove(id);
       }
    }

    @Transactional
    @Override
    public void save(Product product) {
        if (BaiduAuditUtils.TextCensor(product.getName())) {
            productMapper.save(product);
            ProductDetail productDetail = product.getDetail();
            productDetail.setProductId(product.getId());
            productDetailMapper.save(productDetail);
        }else {
            throw  new BusinessException("您输入的是非法字符");
        }

    }

    @Transactional
    @Override
    public void update(Product product) {
        if (BaiduAuditUtils.TextCensor(product.getName())){
        productMapper.update(product);
        Long productId = product.getId();
        ProductDetail productDetail = productDetailMapper.loadByProductId(productId);
        ProductDetail productDetail1 = product.getDetail();
        productDetail1.setId(productDetail.getId());
        productDetail1.setProductId(productId);
        productDetailMapper.update(productDetail1);
        }
        else {
            throw  new BusinessException("您输入的是非法字符");
        }
    }

    @Override
    public void onOrOffSale(int flag, List<Long> ids) {
        if (flag==1){
            //修改上架状态及时间
            Map<String,Object> params = new HashMap<>();
            params.put("onsaleTime",new Date());
            params.put("ids",ids);
            productMapper.onsale(params);
            //update t_product set onsaleTime = xx and state = 1 where id in(1,2,3)
        }else{
            //修改下架状态及时间
            Map<String,Object> params = new HashMap<>();
            params.put("offsaleTime",new Date());
            params.put("ids",ids);
            productMapper.offSale(params);
            //update t_product set offsaleTime = xx and state = 0 where id in(1,2,3)
        }
    }
}
